import { computed, ref, watch, h } from "vue";
import { useRouter, useRoute } from "vue-router";
import { NIcon } from "naive-ui";
import type { MenuOption } from "naive-ui";
import type { RouteRecordRaw } from "vue-router";
import type { Component } from "vue";

// 定义菜单元数据接口
interface MenuMeta {
  title: string;
  icon?: Component;
  hiddenMenu?: boolean;
  sort?: number;
}

// 扩展 vue-router 的 RouteMeta 接口
declare module "vue-router" {
  interface RouteMeta extends Partial<MenuMeta> {}
}

// 渲染图标的辅助函数
function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) });
}

export function useMenus() {
  const router = useRouter();
  const route = useRoute();

  // 菜单选项缓存
  let cachedOptions: MenuOption[] = [];
  let cachedKey = "";

  // 当前展开的菜单keys
  const expandedKeys = ref<string[]>([]);

  // 当前选中的菜单key
  const selectedKey = ref<string>("");

  /**
   * 获取完整路径
   */
  function getFullPath(parentPath: string, childPath: string): string {
    if (childPath.startsWith("/")) {
      return childPath;
    }
    if (childPath === "") {
      return parentPath;
    }
    if (parentPath === "/") {
      return `/${childPath}`;
    }
    // 移除重复的路径段
    const segments = `${parentPath}/${childPath}`
      .split("/")
      .filter(Boolean)
      .reduce((acc, segment) => {
        if (!acc.includes(segment)) acc.push(segment);
        return acc;
      }, [] as string[]);
    return `/${segments.join("/")}`;
  }

  /**
   * 检查菜单项是否有效
   */
  function checkValidMenu(route: RouteRecordRaw): boolean {
    try {
      if (route.meta?.hiddenMenu) {
        return false;
      }

      if (!route.meta?.title) {
        return false;
      }

      if (!route.name) {
        return false;
      }

      if (route.children?.length || route.component || route.redirect) {
        return true;
      }

      return false;
    } catch (error) {
      console.error("Check valid menu failed:", error);
      return false;
    }
  }

  /**
   * 创建菜单项
   */
  function createMenuItem(
    route: RouteRecordRaw,
    parentPath: string = ""
  ): MenuOption {
    try {
      const fullPath = getFullPath(parentPath, route.path);
      const menuItem: MenuOption = {
        label: route.meta?.title || "",
        key: fullPath,
        sort: route.meta?.sort ?? 0,
        icon: route.meta?.icon ? renderIcon(route.meta.icon) : undefined,
      };

      return menuItem;
    } catch (error) {
      console.error("Create menu item failed:", error);
      return {
        label: "Error Item",
        key: "error",
      };
    }
  }

  /**
   * 处理子菜单
   */
  function processChildren(
    route: RouteRecordRaw,
    parentPath: string,
    depth: number = 0
  ): MenuOption[] {
    try {
      if (!route.children || depth > 5) {
        return [];
      }

      const validChildren = route.children.filter(
        (route): route is RouteRecordRaw => checkValidMenu(route)
      );

      return validChildren.map((child) => {
        const fullPath = getFullPath(parentPath, child.path);
        const menuItem = createMenuItem(child, fullPath);

        if (child.children?.length) {
          const childMenus = processChildren(child, fullPath, depth + 1);
          if (childMenus.length) {
            menuItem.children = childMenus;
          }
        }
        return menuItem;
      });
    } catch (error) {
      console.error("Process children failed:", error);
      return [];
    }
  }

  /**
   * 处理单层子菜单
   */
  function processSingleLevelMenu(
    route: RouteRecordRaw,
    parentPath: string
  ): MenuOption[] {
    try {
      if (!route.children) {
        return [];
      }

      const child = route.children[0];
      if (child.meta?.hiddenMenu) {
        const menuItem = createMenuItem(route, parentPath);
        return [menuItem];
      }

      const basePath = route.path.startsWith("/")
        ? route.path
        : `${parentPath}/${route.path}`;
      const fullPath = getFullPath(basePath, child.path);
      const menuItem = createMenuItem(child, fullPath);
      menuItem.icon = route.meta?.icon
        ? renderIcon(route.meta.icon)
        : undefined;

      return [menuItem];
    } catch (error) {
      console.error("Process single level menu failed:", error);
      return [];
    }
  }

  /**
   * 处理普通菜单
   */
  function processNormalMenu(
    route: RouteRecordRaw,
    parentPath: string
  ): MenuOption {
    try {
      const fullPath = route.path.startsWith("/")
        ? route.path
        : getFullPath(parentPath, route.path);

      const menuItem = createMenuItem(route, fullPath);

      if (route.children?.length) {
        const children = processChildren(route, fullPath);
        if (children.length) {
          menuItem.children = children;
        }
      }

      return menuItem;
    } catch (error) {
      console.error("Process normal menu failed:", error);
      return {
        label: "Error Item",
        key: "error",
      };
    }
  }

  /**
   * 判断是否为单层子菜单
   */
  function isSingleLevelMenu(route: RouteRecordRaw): boolean {
    return route.children?.length === 1 && !route.children[0].children?.length;
  }

  /**
   * 获取指定路径的所有父级路径
   */
  function getParentPaths(path: string): string[] {
    const paths: string[] = [];
    const segments = path.split("/").filter(Boolean);
    let currentPath = "";

    segments.forEach((segment) => {
      currentPath = `${currentPath}/${segment}`;
      paths.push(currentPath);
    });

    return paths;
  }

  /**
   * 更新菜单展开和选中状态
   */
  function updateMenuState() {
    const currentPath = route.path;
    expandedKeys.value = getParentPaths(currentPath);
    selectedKey.value = currentPath;
  }

  /**
   * 生成菜单列表
   */
  function generateMenus(
    routes: RouteRecordRaw[],
    parentPath: string = ""
  ): MenuOption[] {
    try {
      const validRoutes = routes.filter((route): route is RouteRecordRaw =>
        checkValidMenu(route)
      );

      const menuList = validRoutes.map((route) => {
        if (isSingleLevelMenu(route)) {
          return processSingleLevelMenu(route, parentPath);
        }
        return processNormalMenu(route, parentPath);
      });

      return menuList
        .flat()
        .sort((a, b) => ((a.sort as number) ?? 0) - ((b.sort as number) ?? 0));
    } catch (error) {
      console.error("Generate menus failed:", error);
      return [];
    }
  }

  /**
   * 获取根路由
   */
  function getRootRoutes(): RouteRecordRaw[] {
    return router.getRoutes().filter((route) => {
      const segments = route.path.split("/").filter(Boolean);
      return segments.length === 0 || segments.length === 1;
    });
  }

  // 计算菜单选项
  const menuOptions = computed(() => {
    const newKey = JSON.stringify(getRootRoutes());
    if (cachedKey === newKey) {
      return cachedOptions;
    }
    cachedKey = newKey;
    cachedOptions = generateMenus(getRootRoutes());
    return cachedOptions;
  });

  // 监听路由变化，更新菜单状态
  watch(
    () => route.path,
    () => {
      updateMenuState();
    },
    { immediate: true }
  );

  return {
    menuOptions,
    expandedKeys,
    selectedKey,
  };
}
